﻿<template>
  <a-modal
    :title="(type==='modify'?'修改':'新增')+'盘点计划'"
    width="90vw"
    dialogClass="zero-modal"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <div class="inventory-plan-modal-content">
        <div class="form-view">
          <a-form :form="form">
            <a-row>
              <a-col :md="12" :sm="24">
                <a-form-item label="计划号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input disabled v-decorator="['planNo',{rules:[{required:true,message:'计划号不可为空！'}]}]" />
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="24">
                <a-form-item label="盘点规则" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select :allowClear="true" style="width: 100%" v-decorator="['inventoryRuleId',{rules:[{required:true,message:'请选择盘点规则！'}]}]" placeholder="请选择...">
                    <a-select-option v-for="(item,index) in ruleOptions" :key="index" :value="item.id">
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="24">
                <a-form-item label="盘点仓库" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select style="width: 100%" v-decorator="['areaID',{rules:[{required:true,message:'请选择盘点仓库！'}]}]" placeholder="请选择...">
                    <a-select-option v-for="(item,index) in areaOptions" :key="index" :value="item.areaId">{{ item.areaName }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="24">
                <a-form-item label="盘点时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-range-picker style="width: 100%" v-decorator="['dateRange',{rules:[{required:true,message:'请确认盘点时间！'}]}]" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <div class="action-view">
          <a-button type="primary" icon="plus" @click="openChoose">
            添加计划明细
          </a-button>
        </div>
        <div class="list-view" ref="listWrapper">
          <!-- 注意scroll.x的值 -->
          <template v-if="th">
            <a-table v-if="type==='modify'" :data-source="list" :columns="columns" :rowKey="tableKey" :pagination="false" :scroll="{x:1100,y:th}">
              <template slot="index" slot-scope="text,record,index">{{index+1}}</template>
              <template slot="action" slot-scope="text,record,index">
                <a-button type="danger" size="small" @click.stop="cancelListItem(index)">删除</a-button>
              </template>
              <span slot="materialTyleSlot" slot-scope="text">{{ 'material_type' | dictType(text) }}</span>
            </a-table>
            <a-table v-else :data-source="list" :columns="columns" :rowKey="tableKey" :pagination="false" :scroll="{x:1100,y:th}">
              <template slot="index" slot-scope="text,record,index">{{index+1}}</template>
              <template slot="action" slot-scope="text,record,index">
                <a-button type="danger" size="small" @click.stop="cancelListItem(index)">删除</a-button>
              </template>
              <span slot="materialTyleSlot" slot-scope="text">{{ 'material_type' | dictType(text) }}</span>
            </a-table>
          </template>
          
        </div>
      </div>
    </a-spin>
    
    <choose-modal :visible.sync="chooseVisible" @callback="chooseBack" />
    
    <template slot="footer">
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button key="submit" type="primary" :loading="confirmLoading" @click="onSubmit" :disabled="!list.length">确认</a-button>
    </template>
  </a-modal>
</template>

<script>
  import {
    InventoryPlanAdd,
    GetBillNumber,
    InventoryPlanEdit,
    InventoryPlanDetailPage
  } from '@/api/modular/main/InventoryPlanManage'
  import ChooseModal from './chooseMaterials.vue'
  import moment from 'moment'
  export default {
    components:{ChooseModal},
    props:{
      type:{
        type:String,
        default:''
      },
      areaOptions:{
        type:Array,
        default:function(){
          return []
        }
      },
      ruleOptions:{
        type:Array,
        default:function(){
          return []
        }
      }
    },
    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 }
        },
        visible: false,
        confirmLoading: false,
        form: this.$form.createForm(this),
        th:0,
        tableKey:'containerCode',
        list:[],
        columns:[
          { title: '序号', key: 'index', width: 70, align:'center', scopedSlots: { customRender: 'index' }},
          { title: '容器编号', dataIndex: 'containerCode', key: 'containerCode' },
          { title: '库位编号', dataIndex: 'placeCode', key: 'placeCode' },
          { title: '物料编码', dataIndex: 'materialCode', key: 'materialCode' },
          { title: '物料名称', dataIndex: 'materialName', key: 'materialName' },
          { title: '物料类型', dataIndex: 'materialType', key: 'materialType', width: 120, scopedSlots: { customRender: 'materialTyleSlot' }},
          { title: '数量', dataIndex: 'stockNumber', key: 'stockNumber' },
          { title: '操作', key: 'action', width: 80, align:'center', scopedSlots: { customRender: 'action' }}
        ],
        chooseVisible:false,
        planid:null
      }
    },
    methods: {
      // 初始化方法
      init (record) {
        this.visible = true
        this.$nextTick(() => {
          this.th = this.$refs.listWrapper.clientHeight - 60
          if (this.type==='modify') {
            this.getEditInitData(record)
          } else {
            this.getAddInitData()
          }
        });
      },
      getAddInitData(){
        this.confirmLoading = true;
        GetBillNumber().then(d=>{
          let formData = {
            planNo:(d.data || '')
          }
          this.form.setFieldsValue(formData)
          this.confirmLoading = false;
        }).catch((err)=>{
          this.confirmLoading = false;
        })
      },
      getEditInitData(record){
        let formData = {
          planNo:record.planNo,
          inventoryRuleId:record.inventoryRuleId,
          areaID:String(record.areaID)
        }
        if (record.startPlanTime) {
          record.startPlanTime = moment(record.startPlanTime).format('YYYY-MM-DD')
        }
        if (record.endPlanTime) {
          record.endPlanTime = moment(record.endPlanTime).format('YYYY-MM-DD')
        }
        if (record.startPlanTime && record.endPlanTime) {
          formData.dateRange = [record.startPlanTime,record.endPlanTime]
        } else {
          formData.dateRange = []
        }
        this.form.setFieldsValue(formData)
        this.confirmLoading = true;
        let params = {
          Id:record.id,
          PageNo:1,
          PageSize:999
        }
        this.planid = record.id
        InventoryPlanDetailPage(params).then((d)=>{
          this.list = d.data.rows || []
          this.confirmLoading = false;
        }).catch(()=>{
          this.confirmLoading = false;
        })
      },
      chooseBack(arr){
        let newArr = [], reCount = 0;
        arr.forEach((item)=>{
          let f = false;
          for (let i=0;i<this.list.length;i++) {
            if (this.list[i][this.tableKey] === item[this.tableKey]) {
              reCount++;
              f = true
              break;
            }
          }
          if (!f) {
            let _obj = {...item}
            _obj.orderQuantity = 0
            _obj.requireTime = ''
            newArr.push(item)
          }
        })
        this.list = [].concat(newArr,this.list)
        if (reCount) {
          this.$message.warning(`${reCount}笔数据已存在，未添加！`);
        }
      },
      cancelListItem(index){
        this.list.splice(index,1)
      },
      openChoose(){
        this.chooseVisible = true
      },
      /**
       * 提交表单
       */
      onSubmit () {
        const { form: { validateFields } } = this
        validateFields((errors, values) => {
          if (!errors) {
            this.confirmLoading = true
            this.handleSubmit(values,(fx)=>{
              if (fx) {
                this.$message.success('提交成功')
                this.confirmLoading = false
                this.handleCancel()
                this.$emit('ok')
              } else {
                this.confirmLoading = false
              }
            })
          } 
        })
      },
      handleSubmit(values,callback){
        this.confirmLoading = true
        let params = {...values}
        if ((params.dateRange instanceof Array) && params.dateRange.length===2) {
          params.startPlanTime = params.dateRange[0] + ' 00:00:00'
          params.endPlanTime = params.dateRange[1] + ' 23:59:59'
          delete params.dateRange
        } else {
          delete params.dateRange
          delete params.startPlanTime
          delete params.endPlanTime
        }
        if (this.type==='modify') {
          this.handleSubmitModify(params,callback)
        } else {
          this.handleSubmitAdd(params,callback)
        }
      },
      handleSubmitAdd(values,callback){
        let params = {...values,...{inventoryPlanModel:this.list}}
        InventoryPlanAdd(params).then(()=>{
          callback && callback(true)
        }).catch(()=>{
          callback && callback(false)
        })
      },
      handleSubmitModify(values,callback){
        let params = {...values,...{inventoryPlanModel:this.list,id:this.planid}}
        InventoryPlanEdit(params).then(()=>{
          callback && callback(true)
        }).catch(()=>{
          callback && callback(false)
        })
      },
      handleCancel () {
        this.form.resetFields()
        this.list = []
        this.planid = null
        this.visible = false
      }
    }
  }
</script>

<style lang="less" scoped>
.inventory-plan-modal-content{
  height: 70vh;
  display: flex;
  flex-direction: column;
  .form-view,.action-view{
    flex-shrink: 0;
  }
  .form-view{
    background-color: #F3F7FA;
    padding-top: 20px;
  }
  .action-view{
    padding: 8px 16px;
  }
  .list-view{
    flex-grow: 1;
    padding: 0 16px;
    overflow: auto;
  }
}
</style>